package com.book.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.book.bean.Book;
import com.book.bean.OrderInfo;
import com.book.bean.OrderListInfo;
import com.book.dao.OrderInfoListDao;
import com.book.util.DBUtil;

public class OrderInfoListDaoImpl implements OrderInfoListDao {

	@Override
	public boolean addOrderInfo(OrderListInfo orderListInfo) throws Exception {
		Connection conn = DBUtil.getConn();
		String sql = "INSERT INTO orderlist_info(order_id,bid,pay,olnum,odate) values(?,?,?,?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setInt(1, orderListInfo.getOrderInfo().getOrder_id());
		ps.setInt(2, orderListInfo.getBook().getBid());
		ps.setDouble(3, orderListInfo.getPay());
		ps.setInt(4, orderListInfo.getOlnum());
		ps.setDate(5, new java.sql.Date(orderListInfo.getOdate().getTime()));
		return ps.executeUpdate() == 1;
	}

	@Override
	public List<OrderListInfo> selectOrderInfo(int orderid) throws Exception {
		//select * from order_info o left join users as u on o.uid=u.uid;
		//select o.order_id,ol.ol_id,u.uid,u.phone,u.address,ol.pay,ol.odate from order_info o left join users as u on o.uid=u.uid left join orderlist_info as ol on o.order_id=ol.order_id;
		//select o.order_id,ol.ol_id,u.uid,b.bname,b.author,u.phone,u.address,ol.odate,ol.pay from order_info o,orderlist_info ol,users u,book b where o.uid=u.uid and o.order_id=ol.order_id and b.bid=ol.bid;
		Connection conn = DBUtil.getConn();
		String sql = "select o.order_id,ol.ol_id,b.bid,b.bname,b.author,ol.odate,ol.olnum,ol.pay "
				+ "from order_info o,orderlist_info ol,book b "
				+ "where o.order_id=ol.order_id and b.bid=ol.bid "
				+ "and ol.order_id=? ";

		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setInt(1, orderid);
		ResultSet rs = psmt.executeQuery();
		List<OrderListInfo> oIlist = new ArrayList<OrderListInfo>();
		while (rs.next()) {
			OrderListInfo oInfo = new OrderListInfo();
			OrderInfo order = new OrderInfo();
			order.setOrder_id(rs.getInt(1));
			oInfo.setOrderInfo(order);
			oInfo.setOl_id(rs.getInt(2));
			Book book = new Book();
			book.setBid(rs.getInt(3));
			book.setBname(rs.getString(4));
			book.setAuthor(rs.getString(5));
			oInfo.setOdate(rs.getDate(6));
			oInfo.setOlnum(rs.getInt(7));
			oInfo.setPay(rs.getDouble(8));
			
			oInfo.setBook(book);
			oIlist.add(oInfo);

		}
		return oIlist;
	}

	

}
